package uhasselt.ontologyplugin;

import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.XsltCompiler;
import net.sf.saxon.s9api.XsltTransformer;
import net.sf.saxon.s9api.XsltExecutable;
import net.sf.saxon.s9api.XdmDestination;
import net.sf.saxon.s9api.SaxonApiException;
import javax.xml.transform.stream.StreamSource;

import java.io.File;
import java.io.StringReader;
public class XsltSkosTransformer extends ToSkosTransformer {
	
	private XsltExecutable _toSkos = null; 
	/**
	 * @param xmlString A serialized xml document
	 * @return The xmlString transformed to RDF/XML in skos
	 */
	public XdmNode transform(String xmlString){
		if(xmlString.equals("")){
			return getEmptrySkosDocument();
		}
		try {
		XsltTransformer xsltTransformer = _toSkos.load();
		//XsltTransformer namespaceTransformer = _removeNamespaces.load();
		XdmDestination result = new XdmDestination();
	
	   // namespaceTransformer.setSource(new StreamSource());
		xsltTransformer.setDestination(result);
		xsltTransformer.setSource(new StreamSource(new StringReader(xmlString)));
		xsltTransformer.transform();
		return result.getXdmNode();
		} catch (SaxonApiException e){
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * Initialise
	 */
	public void initialise(PropertyReader reader,String propertyPrefix) {
		
	//	System.out.println(propertyPrefix +".xsltfilepath");
		try {
		Processor processor = ToSkosTransformer.getProcessorInstance();
	//	DocumentBuilder documentBuilder = processor.newDocumentBuilder();
		XsltCompiler xsltCompiler = processor.newXsltCompiler();
		
		_toSkos = xsltCompiler.compile(new StreamSource(new File(reader.getValue(propertyPrefix +".xsltfilepath"))));
	} catch (SaxonApiException e){
		e.printStackTrace();
	}
	}
}